package com.punai.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.punai.common.core.domain.entity.SysUser;
import com.punai.system.domain.CsLinkRolePermission;
import com.punai.system.domain.CsLinkUserRole;
import com.punai.system.mapper.CsLinkRolePermissionMapper;
import com.punai.system.mapper.CsLinkUserRoleMapper;
import com.punai.system.mapper.SysUserMapper;
import com.punai.system.service.CsLinkRolePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class CsLinkRolePermissionServiceImpl extends ServiceImpl<CsLinkRolePermissionMapper, CsLinkRolePermission> implements CsLinkRolePermissionService {

    @Autowired
    private CsLinkUserRoleMapper csLinkUserRoleMapper;
    @Autowired
    private CsLinkRolePermissionMapper csLinkRolePermissionMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Override
    public Map<String, Set<String>> getPerCodeByUserid(Long userId) {

        SysUser sysUser = sysUserMapper.selectById(userId);

        Long companyId = sysUser.getCompanyId();

        CsLinkUserRole csLinkUserRole = csLinkUserRoleMapper.selectOne(
                Wrappers.<CsLinkUserRole>lambdaQuery()
                        .eq(CsLinkUserRole::getUserid, userId)
        );
        if (csLinkUserRole == null) {
            return new HashMap<>();
        }
        Map<String, Set<String>> resMap = new HashMap<>();
        String roleid = csLinkUserRole.getRoleid();
        List<CsLinkRolePermission> allByRoleid = csLinkRolePermissionMapper.findAllByRoleid(roleid, companyId);
        if (CollUtil.isNotEmpty(allByRoleid)) {
            Map<String, List<CsLinkRolePermission>> keyMap = allByRoleid.stream().collect(Collectors.groupingBy(CsLinkRolePermission::getType));
            keyMap.forEach((k,v) -> {
                Set<String> codes = v.stream().map(CsLinkRolePermission::getCode).collect(Collectors.toSet());
                resMap.put(k,codes);
            });
        }
        return resMap;
    }
}
